<?php
/**
 * Created by PhpStorm.
 * User: 户学
 * Date: 2018/4/24
 * Time: 17:28
 */
if (!defined('BASEPATH')) exit('No direct script access allowed');
class User extends M_Controller
{
    public function index(){
        list($data, $total, $param)	= $this->_limit_page(); // 数据库中分页查询

        $id = (int)$param['id'];
        $this->load->library('dip');

        //截止当前会员统计
        $today = date('Y-m-d 00:00:00',time());
        $latest = date('Y-m-d H:i:s',time());
//        $today = '2018-08-03 00:00:00';
//        $latest = '2018-08-03 23:59:59';
        $resmem = $this->db->where('addtime >=' ,$today)->where('addtime <=' ,$latest)->get('user')->result_array();
        $countmem = count($resmem);

        $this->template->assign(array(
            'list'=>$data,
            'countmem' =>$countmem,
            'total' => $total,
            'param' => $param,
            'auser' => $this->db->where('id', $id)->get('user')->row_array(),
            'pages'	=> $this->get_pagination(dr_url('admin/user/index', array(
                'uid' => $id,
                'total' => $total,
                'search' => IS_POST ? 1 : $this->input->get('search')
            )), $total)
        ));
        $this->template->display('user/index.html');
    }

    private function _where(&$select) {

        $uid = (int)$this->input->get('id');
        $uid = $uid ? $uid : $this->uid;
        $search = $this->input->get('search');
        $cache_file = md5($this->duri->uri(1).$uid.$this->uid.SITE_ID.$this->input->ip_address().$this->input->user_agent()); // 缓存文件名称

        // 存在POST提交时，重新生成缓存文件
        if (IS_POST) {
            $data = $this->input->post('data');
            $this->cache->file->save($cache_file, $data, 3600);
            $search = 1;
            unset($_GET['page']);
        }

        $select->where('id', $uid);

        // 存在search参数时，读取缓存文件
        if ($search == 1) {
            $data = $this->cache->file->get($cache_file);
            if (isset($data['start']) && $data['start'] && $data['start'] != $data['end']) {
                $data['end'] = $data['end'] ? $data['end'] : SYS_TIME;
                $select->where('logintime BETWEEN '.$data['start'].' AND '. $data['end']);
            }
        }

        $data['id'] = $uid;

        return $data;
    }


    /**
     * 修改
     */
    public function edit() {

        $uid = (int)$this->input->get('uid');
        $page = (int)$this->input->get('page')?(int)$this->input->get('page'):0;
        $this->load->model("user_model");
        $data = $this->user_model->get_user($uid);

        !$data && $this->admin_msg(fc_lang('对不起，数据被删除或者查询不存在'));
        // 角色权限验证
        !$this->auth_model->role_level($this->member['adminid'], $data['adminid']) && $this->admin_msg(fc_lang('您无权操作（ta的权限高于你）'));

        $field = array();
//        $MEMBER = $this->get_cache('user');
//        if ($MEMBER['setting']['ucenter'] && is_file(WEBPATH.'api/ucenter/config.inc.php')) {
//            include WEBPATH.'api/ucenter/config.inc.php';
//            include WEBPATH.'api/ucenter/uc_client/client.php';
//        }
//
//        if ($MEMBER['field'] && $MEMBER['group'][$data['groupid']]['allowfield']) {
//            foreach ($MEMBER['field'] as $t) {
//                in_array($t['fieldname'], $MEMBER['group'][$data['groupid']]['allowfield']) && $field[] = $t;
//            }
//        }
//
//        $is_uc = function_exists('uc_user_edit') && $MEMBER['setting']['ucenter'];

        if (IS_POST) {
            $edit = $this->input->post('member');
            $page = (int)$this->input->post('page');
            $post = $this->validate_filter($field, $data);
            $edit['groupid'] = '1';
            if (!$edit['groupid']) {
                $error = fc_lang('先选择一个会员组吧');
            } elseif (isset($post['error'])) {
                $error = $post['msg'];
            } else {
                $post[1]['uid'] = $uid;
//                $post[1]['is_auth'] = (int)$data['is_auth'];
//                $post[1]['complete'] = (int)$data['complete'];
//                $this->db->replace('member_data', $post[1]);
                $this->attachment_handle($uid, $this->db->dbprefix('user').'-'.$uid, $field, $data);
                $pasword = MD5($edit['password']);
                $update = array(
                    'name' => $edit['name'],
                    'pass' => $pasword,
//                    'groupid' => $edit['groupid'],
                );
                // 修改密码
//                $edit['pas'] = trim($edit['password']);
//                if ($edit['password']) {
//                    if (defined('UCSSO_API')) {
//                        $rt = ucsso_edit_password($uid, $edit['password']);
//                        // 修改失败
//                        if (!$rt['code']) {
//                            $this->admin_msg(fc_lang($rt['msg']));
//                        }
//                    }
//                    $update['pas'] = md5(md5($edit['pas']).md5($edit['pas']));
//                    $this->hooks->call_hook('member_edit_password', array('member' => $data, 'password' => $edit['password']));
//                    $this->User_model->add_notice($uid, 1, fc_lang('您的密码被管理员%s修改了', $data['name']));
//                    $this->system_log('修改会员【'.$data['username'].'】密码'); // 记录日志
//                }
                $this->db->where('id', $uid)->update('user', $update);
                // 会员组升级挂钩点
                if ($data['groupid'] != $edit['groupid']) {
                    // 表示审核会员
                    $data['groupid'] == 1 && $this->user_model->update_admin_notice('member/admin/home/index/field/uid/keyword/'.$uid, 3);
                    $this->hooks->call_hook('member_group_upgrade', array('uid' => $uid, 'groupid' => $edit['groupid']));
                    $this->system_log('修改会员【'.$data['username'].'】会员组'); // 记录日志
                }
                $this->system_log('修改会员【'.$data['username'].'】资料'); // 记录日志

                $this->admin_msg(fc_lang('操作成功，正在刷新...'), dr_url('user/user/edit', array('uid' => $uid, 'page' => $page)), 1);
            }
            $this->admin_msg($error, dr_url('user/user/edit', array('uid' => $uid, 'page' => $page)));
        }

        $this->template->assign(array(
            'data' => $data,
            'page' => $page,
            'myfield' => $this->field_input($field, $data, TRUE),
        ));
        $this->template->display('member_edit.html');
    }


    public function ajax_email() {

        $uid = (int)$this->input->get('id');
        $email = $this->input->get('email');

        if (!$email || !preg_match('/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/', $email)) {
            exit(fc_lang('邮箱格式不正确'));
        } elseif ($this->db->where('email', $email)->where('uid<>', $uid)->count_all_results('user')) {
            exit(fc_lang('该邮箱【%s】已经被注册', $email));
        }

        exit(0);
    }


    private function  _limit_page(){
        $page = max((int)$this->input->get_post('page'),1);
        $_total = (int)$this->input->get_post('total');

        if(!$_total){
//            $select = $this->db;
//            $_param = $this->_where($select);
            $_total = $this->db->count_all_results('user');
            if(!$_total){
                return array(array(), 0);
            }
        }

        $select = $this->db;
//        $_param = $this->_where($select);
        $result = $this->db
            ->limit(SITE_ADMIN_PAGESIZE, SITE_ADMIN_PAGESIZE * ($page - 1))
            ->order_by('id desc')
            ->get('user')
            ->result_array();
//        return array($result,$_total, $_param);
        return array($result,$_total);
    }




    public function excelData(){
        $dateone = $_POST['dateone'];
        $datetwo = $this->input->post('datetwo');
        header("Content-type:text/html");
        header("Content-Disposition:attachment;filename=注册用户.xls");

        if (!empty($dateone)&&!empty($datetwo)){
            $array=$this->db->where('addtime >' ,$dateone)->where('addtime <' ,$datetwo)->get("user")->result_array();
        }else{
            $array=$this->db->get("user")->result_array();
        }

        $str="id\t"."姓名\t"."手机号\t"."年级\t"."学科\t"."注册时间\n";
        foreach($array as $val){
            $str.=$val['id']."\t".$val['name']."\t".$val['mobile']."\t".$val['grade']."\t".$val['subject']."\t".$val['addtime']."\n";
        }
        echo $str;
    }


}